package com.yuanjin.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import com.yuanjin.R;

/**
 * @author Administrator 闹钟提醒界面
 */
public class AlarmActivity extends Activity {
	MediaPlayer mp = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// 唤醒屏幕，在setcontentview之前
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		setContentView(R.layout.alarm_main);
		try {
			mp = MediaPlayer.create(this, Uri.parse("/sdcard/Music/mo.mp3"));
			mp.setLooping(true);// 重复播放该音频文件
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		showAlarmDialog();
	}

	private void showAlarmDialog() {
		mp.start();// 播放音频
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("闹钟");
		builder.setMessage("起床啦啦啦啦。。。");
		builder.setPositiveButton("再来一次", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.e("test", "进入再来一次了");

				alarm();
				finish();
			}
		});
		builder.setNegativeButton("停止", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// mp.stop();
				finish();
			}
		});
		builder.setCancelable(false);
		builder.show();
	}

	private void alarm() {
		Log.e("test", "进入alarm了");
		// 获取AlarmManager系统服务对象
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		// 闹钟提醒的时间（毫秒）
		long triggerAtMillis = System.currentTimeMillis() + 3000;
		// 提醒后要触发的intent
		Intent intent = new Intent(this, AlarmActivity.class);
		PendingIntent operation = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		showAlarmDialog();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mp != null) {
			if (mp.isPlaying()) {
				mp.stop();
			}
			mp.release();
		}
	}
}
